package com.bafa.front.events;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bafa.dbcache.LeagueCache;
import com.bafa.front.presentationbeans.LeagueBean;
import com.bafa.front.presentationbeans.PlayerListBean;
import com.bafa.front.presentationbeans.ResultsListBean;
import com.bafa.front.utils.FrontUtils;
import com.bafa.objects.PageBean;
import com.bafa.objects.season.Division;
import com.bafa.objects.season.Season;
import com.bafa.services.ReportServices;
import com.bafa.services.RetrieveServices;

public class DisplayLeagueEvent extends Event {

	@Override
	public void doEvent(HttpServletRequest request,
			HttpServletResponse response, PageBean page) {
		Division division = new Division();
		
		String seasonId = request.getParameter("SeasonId");
		if(seasonId==null)
			seasonId = new Integer(FrontUtils.getThisSeason(request).getId()).toString();
		division = RetrieveServices.getDivision(seasonId,request.getParameter("Division"));
		
		
		Season season = RetrieveServices.getSeason(seasonId);
		String groupDiv = "";
		if(division==null||division.getDivision()==0){
			request.setAttribute("BLANKDIVISION",division);
		}else{
			LeagueBean leagueBean = new LeagueBean(division.teamIdArray(),new Integer(seasonId),division.getDivision(),division.isCompleted());
			String[] scorers = RetrieveServices.getDivisionTopScorers(division.getDivision(),division.getSeasonId()+"");
			ResultsListBean recentResults = new ResultsListBean(division.matchArray());
			request.setAttribute("RECENTRESULTS",recentResults);
			
			request.setAttribute("TOPSCORERS",new PlayerListBean(scorers,new Integer(seasonId),division.getDivision()));
			
			HttpSession session = request.getSession();
			session.setAttribute("DIVISION",leagueBean);
			//session.setAttribute("LEAGUERULES",new LeagueRulesBeans(division.getLeagueRules().getNumRelegated(),division.getLeagueRules().getNumPromoted()));
			if(season.isLeague()){
				groupDiv = "Division "+division.getDivision();
			}else{
				groupDiv = "Group "+division.getDivision();
			}
		}
		
		
		
		
		if(season!=null)page.setMainheader(page.getMainheader().replaceAll("<>",season.getName()+" "+season.getYear()+" "+((season.isLeague())?"League":"Cup")+" "+groupDiv));
		else page.setMainheader(page.getMainheader().replaceAll("<>",""));
		if(season!=null)page.setPageheader(page.getPageheader().replaceAll("<>",season.getName()+" "+season.getYear()+" "+((season.isLeague())?"League":"Cup")+" "+groupDiv));
		else page.setPageheader(page.getPageheader().replaceAll("<>",""));

	}

}
